package com.sengled.cloud.biz.union.mgt.api.config;

import com.sengled.cloud.biz.union.mgt.common.util.FastJsonUtils;
import com.sengled.cloud.biz.union.mgt.model.request.SetAccountStatusRequest;
import com.sengled.cloud.biz.union.mgt.model.response.ResponseMessage;
import com.sengled.cloud.biz.union.mgt.service.sys.impl.AccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
	
	 @Autowired
	 private AccountService accountService;

	
	 
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ResponseMessage res = new ResponseMessage();
        if(authentication != null) {
            System.out.println(authentication.getName());
        }
//        response.setStatus(HttpStatus.OK.value());
     	  try{
    		  if(null==accountService){
    			  ServletContext sc = request.getServletContext();
        		  WebApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(sc);
        		  accountService  = (AccountService) ctx.getBean("accountService"); 
    		  }
    		 
    	      if(accountService!=null&&authentication!=null){
    	    	  String accountName = authentication.getName();
                  setAccountStatus(null,accountName,2);
    	      }
          }catch(Exception e){
        	  response.setCharacterEncoding("UTF-8");
              response.setContentType("application/json");
              response.getWriter().println(FastJsonUtils.toJSONNoFeatures(res));
        	
          }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(FastJsonUtils.toJSONNoFeatures(res));


    }
    
    public void setAccountStatus(Long id,String accountName,Integer status){
    	SetAccountStatusRequest setAccountStatusRequest = new SetAccountStatusRequest();
    	//setAccountStatusRequest.setId(id);
    	setAccountStatusRequest.setAccountName(accountName);
    	setAccountStatusRequest.setAccountStatus(status);
    	//accountService.setAccountStatusById(setAccountStatusRequest);
    	accountService.setAccountStatusByName(setAccountStatusRequest);
    }
}
